#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include <pthread.h>

using namespace std;

struct ThreadData
{
    int sockfd;
};

void Usage(std::string order)
{
    std::cout << "\r\nUsage:" << order << " ip port" << std::endl;
}

void *Read(void *argv)
{
    ThreadData *Data = static_cast<ThreadData *>(argv);

    char buf[1024];
    while (1)
    {
        read(Data->sockfd, buf, sizeof(buf));
        //cout << "---------------------" << endl;
        cout << buf << endl;
        memset(buf, 0, sizeof(buf));
    }
    return nullptr;
}

void *Write(void *argv)
{
    ThreadData *Data = static_cast<ThreadData *>(argv);

    while (1)
    {
        std::cerr << "please enter#";
        string message;
        getline(std::cin, message);
        write(Data->sockfd, message.c_str(), message.size());
    }

    return nullptr;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    
    while(true)
    {
    //服务器把读端关闭后，连通客户端资源一起释放，所以不能进行二次读写，需要重新创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in server;
    socklen_t len = sizeof(server);
    memset(&server, 0, len);
    uint16_t port = std::stoi(argv[2]);
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    inet_aton(argv[1], &(server.sin_addr));

    //connect(sockfd, (const sockaddr *)&server, len);

    // ThreadData data;
    // data.sockfd = sockfd;
    // pthread_t read_;
    // pthread_t write_;
    // pthread_create(&read_, nullptr, Read, &data);
    // pthread_create(&write_, nullptr, Write, &data);

    // pthread_join(read_, nullptr);
    // pthread_join(write_, nullptr);

    char buf[1024];
    // while (1)
    // {
        connect(sockfd, (const sockaddr *)&server, len);
        std::cout << "please enter#";
        string message;
        getline(std::cin, message);
        write(sockfd, message.c_str(), message.size());

        read(sockfd, buf, sizeof(buf));
        //cout << "---------------------" << endl;
        cout << buf << endl;
        memset(buf, 0, sizeof(buf));


        close(sockfd);
    }

    return 0;
}